package com.library.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.library.entity.Category;
import com.library.mapper.CategoryMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类服务
 */
@Service
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {
    
    /**
     * 获取分类树
     */
    public List<Category> getCategoryTree() {
        // 查询所有分类
        List<Category> allCategories = this.list(new LambdaQueryWrapper<Category>()
                .orderByAsc(Category::getSort));
        
        // 构建树形结构
        return allCategories.stream()
                .filter(category -> category.getParentId() == 0)
                .peek(category -> category.setChildren(getChildren(category.getId(), allCategories)))
                .collect(Collectors.toList());
    }
    
    /**
     * 递归获取子分类
     */
    private List<Category> getChildren(Long parentId, List<Category> allCategories) {
        return allCategories.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .peek(category -> category.setChildren(getChildren(category.getId(), allCategories)))
                .collect(Collectors.toList());
    }
    
    /**
     * 获取所有顶级分类
     */
    public List<Category> getTopCategories() {
        return this.list(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, 0)
                .orderByAsc(Category::getSort));
    }
}

